// pages/work-order/order-detail/index.ts
import {detail} from '../../../api/secret_realm'
import { LENGYU_SUCCESS_CODE } from '../../../utils/request';
//@ts-ignore 
import * as echarts from "../../../components/ec-canvas/echarts"; //引入外部的js工具类

function hasProperty<T, K extends keyof T>(obj: T, key: K): obj is T & Record<K, unknown> {
  return key in obj;
}

function setOption(chart:any, characters:any,dataType:string) {
  let xdata:string[]=[];
  let ydata:any=[]
 if(characters){
  characters.sort((a, b) => {
    if(!hasProperty(a, dataType)){
      return -1
    }
    else if(!hasProperty(b, dataType)){
      return 1
    }
    
    return (a[dataType] - b[dataType])
  });
   characters.forEach(element => {
      xdata.push(element.name)
      let color = getCareerColor(element.career);
      let tmpValue=0;
      if(hasProperty(element, dataType) && element[dataType]){
        tmpValue=element[dataType]
      }
      let tmpYData = {
        value:tmpValue,
        itemStyle: {color: color}
      }
      ydata.push(tmpYData)
   });
 }
 console.log(ydata)
  const option = {
      title: {
          // text: dataType,
          padding: [10, 0, 0, 20],
          textStyle: {
              fontSize: 14,
              color: '#696969'
          },
          top: '10rpx'
      },
      legend:{
        // left: '200px',
        // right: '200px%',
        // width:'30%'
      },
      backgroundColor: "#fff",
      // color: ["#006EFF", "#67E0E3", "#9FE6B8"],
      animation: false,
      grid: {
          show: true,
          left:'20%'
      },
      yAxis: {
          type: 'category',
          data: xdata,      //x轴上的数据是动态的，所以我作为参数传进来
          axisLabel: {
              fontSize: 10,
              formatter: function (value:any) {
                  if(value){
                    var val = value.split("-")[0]
                    return val
                  }
              },
          }
      },
      xAxis: {
          x: 'center',
          scale: true,
          type: 'value',
          min: 0,
          axisLabel: {
              formatter: function (value:any) {
                if(dataType == "dps" || dataType=="hps"){
                      var val = value / 10000 + 'W';
                      return val
                }
              }
         
          }
      },
      series: [{
          type: 'bar',
          data: ydata,  
          symbol: 'none',
          label: {
            show: true, // 显示标签
            position: 'inside', // 标签显示在柱子顶部,
            formatter: function (value:any) {
              if(dataType == "dps" || dataType=="hps"){
                  var val = (value.data.value / 10000).toFixed(2) + 'W';
                  return val
              }
            }
          },
          lineStyle: {
              width: 1
          },
          barMinHeight:'80',
          barWidth:'70%'
      }]
  };
  chart.setOption(option)
}

function getCareerColor(career:string){
  let color:string="#000000"
  if(career == "骑士"){
    color='#db7fa4'
  }
  else if(career == "萨满祭司"){
    color="#2253e4"
  }
  else if(career == "战士"){
    color="#b18d64"
  }
  else if(career == "潜行者"){
    color="#e5de61"
  }
  else if(career == "死亡骑士"){
    color="#b01e37"
  }
  else if(career == "恶魔猎手"){
    color="#932eb3"
  }
  else if(career == "牧师"){
    color="#e8e8e8"
  }
  else if(career == "法师"){
    color="#61bbd9"
  }
  else if(career == "术士"){
    color="#8577b3"
  } else if(career == "唤魔师"){
    color="#308773"
  }
  else if(career == "武僧"){
    color="#00e688"
  }
  else if(career == "猎人"){
    color="#8db461"
  }
  else if(career == "德鲁伊"){
    color="#e4720a"
  }
  return color;
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    realm:{
      id:"",
      affixIdArray:"",
      characters:[]
    },
    ecDps: {
      lazyLoad: true
    },
    Mychart:null,
    chartType:"dps"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(option:any) {
    console.log(option)
    var _this = this;
    if(option && option.id){
      this.getDetailData(option.id);
    }

    // this.getOneOption();
    // this.getTwoOption();
    // this.setData({                    //每隔一分钟刷新一次
    //     timer: setInterval(function () {
    //             _this.getOneOption();
    //             _this.getTwoOption();
    //         }, 60000)
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
   
  },

  init_one (characters:any,chart:any,dataType:string) {           //初始化第一个图表
    let that = this
    chart.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
            width: width,
            height: height
        });
        setOption(chart,characters,dataType)
        return chart;
    });
},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.data.realm.id){
      this.getDetailData(this.data.realm.id)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  echartTabSelect(e:any){
    this.setData({
      chartType:e.currentTarget.dataset.charttype
    });
    let dpsChart = this.selectComponent('#dps-chart');  
    this.init_one (this.data.realm.characters,dpsChart,e.currentTarget.dataset.charttype)
  },
  async getDetailData(id:string){
    let result = await detail(id);
    if(result.code == LENGYU_SUCCESS_CODE && result.data){
      this.setData({
        'realm':result.data
      })
      console.log("result",result)
      this.setData({
        'realm.affixIdArray':result.data.affixIds.replace("[","").replace("]","").split(",")
      })
    
      try {
        let jsonArray = JSON.parse(result.data.characters, (key, value) =>
          key === "" ? value : value
        );
        console.log(jsonArray);
        result.data.characters = jsonArray;
        this.setData({
          'realm.characters':jsonArray
        })
      } catch (error) {
        console.error("Parsing error:", error);
        this.setData({
          'realm.characters':[]
        })
      }
      let dpsChart = this.selectComponent('#dps-chart');  
      this.init_one (this.data.realm.characters,dpsChart,"dps")
    }
    else{
      this.setData({
    
      })
    }
   
    console.log(result);
  },
  previewOrderImage(e:any){
    console.log("图片预览",e)
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: e.currentTarget.dataset.urls // 需要预览的图片http链接列表
    })
  },
  gotoProcOrder(e:any){
    console.log("跳转处理页面")
    wx.navigateTo({
      url:"/pages/work-order/order-proc/index?id=" + this.data.realm.id,
    })
  },

 
})